package com.atguigu.day06;

import org.apache.flink.api.common.eventtime.SerializableTimestampAssigner;
import org.apache.flink.api.common.eventtime.WatermarkStrategy;
import org.apache.flink.api.common.state.ValueState;
import org.apache.flink.api.common.state.ValueStateDescriptor;
import org.apache.flink.api.common.typeinfo.Types;
import org.apache.flink.api.java.tuple.Tuple2;
import org.apache.flink.streaming.api.datastream.SingleOutputStreamOperator;
import org.apache.flink.streaming.api.environment.StreamExecutionEnvironment;
import org.apache.flink.streaming.api.functions.windowing.ProcessWindowFunction;
import org.apache.flink.streaming.api.windowing.assigners.TumblingEventTimeWindows;
import org.apache.flink.streaming.api.windowing.time.Time;
import org.apache.flink.streaming.api.windowing.windows.TimeWindow;
import org.apache.flink.util.Collector;
import org.apache.flink.util.OutputTag;

import java.time.Duration;
//a 1
//a 2
//a 3
//a 10
//a 1
//a 1
//a 15
//a 1
public class Example6 {
    public static void main(String[] args) throws Exception {
        StreamExecutionEnvironment env = StreamExecutionEnvironment.getExecutionEnvironment();
        env.setParallelism(1);

        SingleOutputStreamOperator<String> result = env
                .socketTextStream("hadoop102", 9999)
                .map(r -> Tuple2.of(r.split(" ")[0], Long.parseLong(r.split(" ")[1]) * 1000L))
                .returns(Types.TUPLE(Types.STRING, Types.LONG))
                .assignTimestampsAndWatermarks(
                        WatermarkStrategy.<Tuple2<String, Long>>forBoundedOutOfOrderness(Duration.ofSeconds(5))
                                .withTimestampAssigner(new SerializableTimestampAssigner<Tuple2<String, Long>>() {
                                    @Override
                                    public long extractTimestamp(Tuple2<String, Long> element, long recordTimestamp) {
                                        return element.f1;
                                    }
                                })
                )
                .keyBy(r -> r.f0)
                .window(TumblingEventTimeWindows.of(Time.seconds(5)))
                .sideOutputLateData(new OutputTag<Tuple2<String, Long>>("late-event") {
                })
                // 窗口等待迟到事件多长时间
                .allowedLateness(Time.seconds(5))
                .process(new ProcessWindowFunction<Tuple2<String, Long>, String, String, TimeWindow>() {
                    @Override
                    public void process(String s, Context context, Iterable<Tuple2<String, Long>> elements, Collector<String> out) throws Exception {
                        // 当前窗口可见的状态变量
                        // 用来标志是否是窗口的第一次触发计算
                        // 单例
                        ValueState<Boolean> isFirstTrigger = context.windowState().getState(new ValueStateDescriptor<Boolean>("is-first", Types.BOOLEAN));

                        if (isFirstTrigger.value() == null) {
                            // 当窗口第一次触发时
                            out.collect("窗口第一次触发，窗口：" + context.window().getStart() + "~" + context.window().getEnd() + "" +
                                    "中共有" + elements.spliterator().getExactSizeIfKnown());
                            // 将标志位置为true
                            isFirstTrigger.update(true);
                        } else if (isFirstTrigger.value() != null && isFirstTrigger.value()) {
                            out.collect("迟到数据到达，窗口：" + context.window().getStart() + "~" + context.window().getEnd() + "" +
                                    "中共有" + elements.spliterator().getExactSizeIfKnown());
                        }
                    }
                });

        result.print("主流");
        result.getSideOutput(new OutputTag<Tuple2<String, Long>>("late-event"){}).print("侧输出流");

        env.execute();
    }
}

